package com.atguigu.orderservice.service.impl;

import com.atguigu.commonutils.vo.CourseWebVoForPay;
import com.atguigu.commonutils.vo.UcenterMemberPay;
import com.atguigu.orderservice.client.EduClient;
import com.atguigu.orderservice.client.UcenterClient;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.mapper.TOrderMapper;
import com.atguigu.orderservice.service.TOrderService;
import com.atguigu.orderservice.utils.OrderNoUtil;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-12-04
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    private EduClient eduClient;

    @Autowired
    private UcenterClient ucenterClient;

    //根据课程id+用户id生成订单信息
    @Override
    public String createOrder(String courseId, String memberId) {
        //1根据工具类生成订单编号
        String orderNo = OrderNoUtil.getOrderNo();
        //2根据课程id获取课程信息
        CourseWebVoForPay courseInfoForOrder  = eduClient.getCourseInfoForOrder(courseId);
        //2.1验空
        if (courseInfoForOrder == null) {
            throw new GuliException(20001, "获取课程信息失败");
        }
        //3根据用户id获取用户信息
        UcenterMemberPay ucenterInfoOrder = ucenterClient.getUcenterInfoOrder(memberId);
        //3.1验空
        if (ucenterInfoOrder == null) {
            throw new GuliException(20001, "获取用户信息失败");
        }
        //4补全信息后，订单信息存入数据库
        TOrder order  = new TOrder();
        order.setOrderNo(orderNo);
        order.setCourseId(courseId);
        order.setCourseTitle(courseInfoForOrder.getTitle());//课程标题
        order.setCourseCover(courseInfoForOrder.getCover());//课程封面图片路径
        order.setTeacherName(courseInfoForOrder.getTeacherName());
        order.setTotalFee(courseInfoForOrder.getPrice());//订单金额
        order.setMemberId(memberId);//会员id
        order.setMobile(ucenterInfoOrder.getMobile());//手机号
        order.setNickname(ucenterInfoOrder.getNickname());
        order.setStatus(0);//0：未支付 1：已支付
        order.setPayType(1);//1：微信 2：支付宝
        baseMapper.insert(order);

        return orderNo;
    }
}
